## main.py
import sys
import argparse
from typing import Dict, Optional, List, Tuple
import logging

# Attempt to import required packages with error handling
try:
    import pymysql
    from pypinyin import pinyin, Style
except ImportError as e:
    logging.error(f"Missing required packages: {e}")
    sys.exit(1)

class DBConnector:
    """Handles database connections and operations."""
    def __init__(self, connection_params: Dict[str, str]):
        self.connection_params = connection_params
        self.connection: Optional[pymysql.connections.Connection] = None

    def connect(self) -> pymysql.connections.Connection:
        """Establishes a connection to the database."""
        if self.connection is not None:
            return self.connection
        try:
            self.connection = pymysql.connect(**self.connection_params)
        except pymysql.MySQLError as e:
            logging.error(f"Error connecting to MySQL Platform: {e}")
            sys.exit(1)
        return self.connection

    def get_field_type(self, table_name: str, field_name: str) -> str:
        """Retrieves the data type of a specified field in a table."""
        try:
            with self.connect().cursor() as cursor:
                cursor.execute(f"SHOW FIELDS FROM {table_name} WHERE Field = %s", (field_name,))
                result = cursor.fetchone()
                if result:
                    print("result",result[1])
                    return result[1]  # Field type is in the second column
                else:
                    return ""
        except pymysql.MySQLError as e:
            logging.error(f"Error fetching field type: {e}")
            return ""

    def retrieve_field_data(self, table_name: str, field_name: str) -> List[Tuple]:
        """Fetches the data of a specified field from a table."""
        try:
            with self.connect().cursor() as cursor:
                cursor.execute(f"SELECT {field_name} FROM {table_name}")
                return cursor.fetchall()  # Returns all rows
        except pymysql.MySQLError as e:
            logging.error(f"Error fetching field data: {e}")
            return []

    def update_field_data(self, table_name: str, field_name: str, data: List[Tuple[str, str]]) -> bool:
        """Updates the data of a specified field in a table."""
        try:
            with self.connect().cursor() as cursor:
                update_query = f"UPDATE {table_name} SET {field_name} = %s WHERE {field_name} = %s"
                cursor.executemany(update_query, data)
                self.connect().commit()
                return True
        except pymysql.MySQLError as e:
            logging.error(f"Error updating field data: {e}")
            return False

class PinyinConverter:
    """Converts Chinese characters to Pinyin."""
    @staticmethod
    def convert_to_pinyin(text: str) -> str:
        """Converts text to Pinyin."""
        return ''.join([item[0] for item in pinyin(text, style=Style.FIRST_LETTER)])

class Utils:
    """Contains utility functions for the application."""
    @staticmethod
    def parse_command_line_args() -> Dict[str, str]:
        """Parses command line arguments."""
        parser = argparse.ArgumentParser(description="Convert Chinese characters to Pinyin.")
        parser.add_argument("--host",type=str,required=True,help="The host of the database")
        parser.add_argument("--user",type=str,required=True,help="The user of the database")
        parser.add_argument("--password",type=str,required=True,help="The password of the database")
        parser.add_argument("--database",type=str,required=True,help="The database name")
        parser.add_argument("--port",type=int,required=True,help="The port of the database")
        parser.add_argument('--table_name', type=str, required=True, help='The name of the database table.')
        parser.add_argument('--field_name', type=str, required=True, help='The name of the field in the table to convert.')
        args = parser.parse_args()
        return vars(args)

def main():
    """Main function to orchestrate the conversion process."""
    args = Utils.parse_command_line_args()
    db_connector = setup_db_connection(args)
    process_data(args, db_connector)

def setup_db_connection(args:Dict[str,str]) -> DBConnector:
    """Sets up database connection."""
    print(args)
    connection_params = {
        "host": args["host"],
        "port":args["port"],
        "user": args["user"],
        "password": args["password"],
        "database": args["database"],
        "charset": "utf8mb4"
    }
    return DBConnector(connection_params)

def process_data(args: Dict[str, str], db_connector: DBConnector):
    """Processes data based on command line arguments."""
    field_type = db_connector.get_field_type(args['table_name'], args['field_name'])
    logging.info(f"Field type: {field_type},table_name: {args['table_name']},field_name: {args['field_name']}")

    if  'varchar' in field_type:
        data = db_connector.retrieve_field_data(args['table_name'], args['field_name'])
        pinyin_data = [(PinyinConverter.convert_to_pinyin(text[0]), text[0]) for text in data]
        if db_connector.update_field_data(args['table_name'], args['field_name'], pinyin_data):
            logging.info("Conversion to Pinyin completed successfully.")
        else:
            logging.error("Failed to update the database.")
    else:
        logging.info("Field is not of type varchar. No conversion performed.")

if __name__ == "__main__":
    logging.basicConfig(level=logging.INFO)
    main()
